<template>
  <div>
    <el-form label-position="right" size="small" label-width="80px" class="base-search-more">
      <el-row>
        <el-col :span="6">
          <el-form-item label="区域">
            <el-input style="width: 100%;" placeholder="输入区域名称" v-model="params.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号">
            <el-input style="width: 100%;" placeholder="请输入手机号" v-model="params.mobile" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSizeChange(10)">查询</el-button>
            <el-button type="primary" plain icon="el-icon-plus" @click="addCityManager(1)">新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="base-table-wrap">
      <el-table :data="tableData.list" stripe style="width: 100%">
        <el-table-column prop="realname" label="城市经理名称" min-width="160" align="center"></el-table-column>
        <el-table-column prop="mobile" label="联系方式" min-width="160" align="center"></el-table-column>
        <el-table-column prop="username" label="登录账号" min-width="160" align="center"></el-table-column>
        <el-table-column prop="rname" label="所属角色" min-width="120" align="center"></el-table-column>
        <el-table-column prop="createtime" label="账号创建时间" min-width="100" align="center"></el-table-column>
        <el-table-column prop="modifytime" label="最后登录时间" min-width="100" align="center"></el-table-column>
        <el-table-column fixed="right" label="操作" width="140" align="center">
          <template slot-scope="scopes">
            <el-button class="el-text-check" type="text" @click="addCityManager(2,scopes.row)">编辑</el-button>
            <el-button class="el-text-warning" type="text" @click="changePass(scopes.row.id)">修改密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="base-directives-loading" v-show="isloadingTable">
        <div class="el-loading-spinner">
          <svg viewBox="25 25 50 50" class="circular">
            <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
          </svg>
        </div>
      </div>
      <div class="base-pagination clearfix">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="newPage" :page-sizes="[10, 20, 30, 40]" background :pageSize='pageSize'
          layout="total,sizes, prev, pager, next, jumper" :total="tableData.total" />
      </div>
    </div>
    <el-dialog :title="form.id?'修改城市经理':'添加城市经理'" v-dialogDrag :visible.sync="dialogTableVisible" width="800px" :close-on-press-escap="true">
      <el-form :model="form" ref="ruleForm" label-width="120px" class="demo-ruleForm" size="small">
        <el-form-item label="登录账号" prop="username" :rules="[{ required: true, message: '请输入账号名称', trigger: 'blur' }]">
          <el-input v-model="form.username" placeholder="6-14位字符，可由字母、数字组成" />
        </el-form-item>
        <el-form-item label="城市经理名称" prop="realname" :rules="[{ required: true, message: '请输入员工姓名', trigger: 'blur' }]">
          <el-input v-mode="form.realname" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" :rules="[{required: true, message: '手机号未填', trigger: 'blur'}]">
          <el-input v-model="form.mobile" type="number" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="指定区域" prop='agentids' :rules="[{type:'array', required: true, message: '请选择区域', trigger: 'change' }]">
          <agent-list style="width:100%" :agentids="form.agentids" v-on:listenToChildEvent="getAentId" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')" :loading='isloadingsubmit'>保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="修改密码" v-dialogDrag :visible.sync="dialogPassVisible" width="480px" :close-on-press-escap="true" >
      <el-form :model="ruleForm" status-icon ref="ruleForm2" label-width="85px" size='large'>
        <el-form-item label="新密码" prop="password" :rules="[
          { min: 6, max: 18, message: '密码6到18个字符', trigger: 'blur'},
          { validator: validatePass1, trigger: 'blur'}]">
          <el-input v-model="ruleForm.password" type="password" />
        </el-form-item>
        <el-form-item label="确认新密码" prop="password1" :rules="[
          { validator: validatePass2, trigger: 'blur'},
          { min: 6, max: 18, message: '密码6到18个字符', trigger: 'blur'}]">
          <el-input v-model="ruleForm.password1" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm2('ruleForm2')" :loading='isloadingsubmit'>保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import agentList from './components/cityManageList'
  import imd5 from '@/utils/md5.js'
  export default {
    components: {
      agentList,
    },
    data() {
      return {
        params: { //查询数据
          page: 0,
          size: 10,
          mobile: '',
          name: ''
        },
        form: {
          username: '',
          realname: '',
          mobile: '',
          agentids: [],
          id: '',
        },
        ruleForm:{
          id:'',
          password: '',
          password1: '',
        },
        isloadingTable: false,
        isloadingsubmit:false,
        dialogTableVisible: false,
        dialogPassVisible: false,
        tableData: {}, // 表单数据
        pageSize:10,
        newPage: 1, // 显示当前page
      }
    },

    methods: {
      validatePass1(rule, value, callback) {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.password1 !== '') {
            this.$refs.ruleForm2.validateField('password1');
          }
          callback();
        }
      },
      validatePass2(rule, value, callback) {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      },
      addCityManager(type, row) {
        this.dialogTableVisible = true
        if (type == 1) {
          this.$nextTick(() => {
            this.$refs['ruleForm'].resetFields();
            this.form.id = ''
          });
        } else if (type == 2) {
          this.$nextTick(() => {
            this.form.username = row.username
            this.form.realname = row.realname
            this.form.mobile = row.mobile
            this.form.agentids = row.agentids?JSON.parse('[' + row.agentids + ']'):[]
            this.form.id = row.id
          });
        }
      },
      changePass(id) {
        this.dialogPassVisible = true
        this.$nextTick(() => {
          this.$refs['ruleForm2'].resetFields();
        });
        this.ruleForm.id = id||null
      },
      getAentId(item) { // 获取子组件传递的区域
        this.form.agentids = item
      },
      handleSizeChange(size) { // 切换条数
        this.params.size = size
        this.pageSize = size
        this.newPage = 1
        this.params.page = 0
        this.getTableList()
      },
      handleCurrentChange(page) { // 切换分页
        this.params.page = page - 1
        this.getTableList()
      },
      getTableList() { // 查找城市经理
        const params = { ...this.params }
        this.isloadingTable = true
        this.$http.get('/server/cityManager/cityManagerlist?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.tableData = res.data.data
          }
        }).finally(() => { this.isloadingTable = false })
      },
      submitForm(ruleForm) { //提交城市经理
        this.$refs[ruleForm].validate((valid) => {
          if (valid) {
            const params = { ...this.form }
            params.agentids = params.agentids.length > 0 ? params.agentids.join(',') : ''
            this.isloadingsubmit = true
            if (params.id) {
              this.$http.post('/server/cityManager/update', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.dialogTableVisible = false
                  this.getTableList()
                }
              }).finally(() => { this.isloadingsubmit = false })
            } else {
              delete params.id
              this.$http.post('/server/cityManager/save', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.dialogTableVisible = false
                  this.handleSizeChange()
                }
              }).finally(() => { this.isloadingsubmit = false })
            }
          } else {
            this.$message.error('有不合法的输入，请检查页面修改再提交')
            return false
          }
        })
      },
      submitForm2(ruleForm) {//提交密码修改
        this.$refs[ruleForm].validate((valid) => {
          if (valid) {
            const params = {
              id: this.ruleForm.id,
              password: imd5.md5(this.ruleForm.password1)
            }
            this.isloadingsubmit = true
            this.$http.get('/server/cityManager/setPassword?'+ this.qs.stringify(params)).then(res => {
              if (res.data.success) {
                this.$message.success('密码修改成功')
                this.dialogPassVisible = false
              }
            }).finally(() => { this.isloadingsubmit = false })
          } else {
            this.$message.error('有不合法的输入，请检查页面修改再提交')
            return false
          }
        })
      }
    },
    mounted() {
      this.getTableList()
    }
  }
</script>
<style scoped>
</style>
